package com.jiaoyou.baojian.activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.jiaoyou.baojian.R;
import com.jiaoyou.baojian.dialog.ImageSelectDialog;
import com.jiaoyou.baojian.entity.RoomEntity;
import com.jiaoyou.baojian.entity.UploadEntity;
import com.jiaoyou.baojian.entity.response.RoomItemResponse;
import com.jiaoyou.baojian.http.Api;
import com.jiaoyou.baojian.http.BaofangCallback;
import com.jiaoyou.baojian.http.response.BaseResponse;
import com.jiaoyou.baojian.utils.Utils;
import com.jph.takephoto.app.TakePhoto;
import com.jph.takephoto.app.TakePhotoImpl;
import com.jph.takephoto.compress.CompressConfig;
import com.jph.takephoto.model.CropOptions;
import com.jph.takephoto.model.InvokeParam;
import com.jph.takephoto.model.TContextWrap;
import com.jph.takephoto.model.TResult;
import com.jph.takephoto.model.TakePhotoOptions;
import com.jph.takephoto.permission.InvokeListener;
import com.jph.takephoto.permission.PermissionManager;
import com.jph.takephoto.permission.TakePhotoInvocationHandler;

import java.io.File;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;

public class CreateBaofangActivity extends BaseActivity implements TakePhoto.TakeResultListener,InvokeListener{

    @BindView(R.id.left_button)
    ImageView leftButton;
    @BindView(R.id.header_title)
    TextView headerTitle;
    @BindView(R.id.right_button)
    ImageView rightButton;
    @BindView(R.id.add)
    RelativeLayout add;
    @BindView(R.id.title)
    EditText title;
    @BindView(R.id.desc)
    EditText desc;
    @BindView(R.id.create)
    Button create;
    @BindView(R.id.cover)
    ImageView cover;

    private TakePhoto takePhoto;
    private InvokeParam invokeParam;
    private CropOptions cropOptions;
    private Uri outputUri;
    private String roomCoverUrl;

    private String groupId;

    private RoomEntity lastClosedPublicRoom;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        getTakePhoto().onCreate(savedInstanceState);
        super.onCreate(savedInstanceState);

        ButterKnife.bind(this);

        File file = new File(Environment.getExternalStorageDirectory(),
                "/temp/" + Utils.randomString8() + ".jpg");
        if (!file.getParentFile().exists())
            file.getParentFile().mkdirs();
        outputUri = Uri.fromFile(file);
        cropOptions = getCropOptions();
        configTakePhotoOption();
        configCompress();

        setTitle("创建包房");

        lastClosedPublicRoom = (RoomEntity) getIntent().getSerializableExtra("room");
        if(lastClosedPublicRoom != null){
            title.setText(lastClosedPublicRoom.name);
            desc.setText(lastClosedPublicRoom.description);
            roomCoverUrl = lastClosedPublicRoom.img;
            cover.setVisibility(View.VISIBLE);
            Utils.showImage(this, lastClosedPublicRoom.img, cover);
        }
    }

    @Override
    public int getContentView() {
        return R.layout.activity_create_baofang;
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        getTakePhoto().onSaveInstanceState(outState);
        super.onSaveInstanceState(outState);
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        getTakePhoto().onActivityResult(requestCode, resultCode, data);
        super.onActivityResult(requestCode, resultCode, data);
    }

    @OnClick({R.id.create, R.id.add})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.create:
                final String titleString = title.getEditableText().toString();
                final String descption = desc.getEditableText().toString();
                if(TextUtils.isEmpty(titleString) || TextUtils.isEmpty(descption) || TextUtils.isEmpty(roomCoverUrl)) {
                    toast("包房名称，描述，背景图都不能为空");
                    return;
                }
                waiting("包房创建中...");
                //TODO 告诉后台，这里不提交文字聊天群的id了
                createRoom(0, Utils.generalChannelName(getLoginResponse().userInfo.userId), titleString, descption);
                break;
            case R.id.add:
                showImageSelectDialog(new ImageSelectDialog.OnImageSelectListener() {
                    @Override
                    public void onSelectCamera() {
                        generalOutputUri();
                        getTakePhoto().onPickFromCaptureWithCrop(outputUri, cropOptions);
                    }

                    @Override
                    public void onSelectGallery() {
                        generalOutputUri();
                        getTakePhoto().onPickFromGalleryWithCrop(outputUri, cropOptions);
                    }
                });
                break;
        }
    }

    private void createRoom(final long tribeId, final String channelName, String title, String desc){
        Api.getInstance().createRoom(tribeId, channelName, roomCoverUrl, title, desc, new BaofangCallback<RoomItemResponse>() {
            @Override
            public void onFailure(Call call, Throwable t) {
                stopWaiting();
                toast("错误：" + t.getLocalizedMessage());
            }

            @Override
            public void onSuccess(RoomItemResponse roomItemResponse) {
                stopWaiting();
                Bundle bundle = new Bundle();
                bundle.putSerializable("room", roomItemResponse);
                startActivity(RoomActivity.class, bundle);
                finish();
            }
        });
    }

    @Override
    public void takeSuccess(final TResult result) {
        ///data/user/0/com.jiaoyou.baojian/cache/takephoto_cache/1494340603729.jpg
        waiting("上传图片...");
        Api.getInstance().uploadRoomBgImage(new File(result.getImage().getCompressPath()), new BaofangCallback<UploadEntity>(){

            @Override
            public void onFailure(Call<BaseResponse<UploadEntity>> call, Throwable t) {
                stopWaiting();
                toast("上传失败：" + t.getLocalizedMessage());
            }

            @Override
            public void onSuccess(UploadEntity uploadEntity) {
                stopWaiting();
                roomCoverUrl = uploadEntity.relativePath;
                cover.setVisibility(View.VISIBLE);
                Glide.with(CreateBaofangActivity.this).load(result.getImage().getCompressPath()).crossFade().into(cover);
            }
        });
    }

    @Override
    public void takeFail(TResult result, String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
    }

    @Override
    public void takeCancel() {
//        Toast.makeText(this, "取消", Toast.LENGTH_LONG).show();
    }

    private void configTakePhotoOption(){
        TakePhotoOptions.Builder builder = new TakePhotoOptions.Builder();
        builder.setWithOwnGallery(false);
        builder.setCorrectImage(true);
        getTakePhoto().setTakePhotoOptions(builder.create());
    }
    private void configCompress(){
        CompressConfig config;
        config = new CompressConfig.Builder()
                .setMaxSize(100 * 1024)
                .setMaxPixel(600)
                .enableReserveRaw(true)
                .create();
        getTakePhoto().onEnableCompress(config, true);
    }
    private CropOptions getCropOptions(){
        CropOptions.Builder builder=new CropOptions.Builder();
        builder.setAspectX(10).setAspectY(4);
        builder.setWithOwnCrop(false);
        return builder.create();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        //以下代码为处理Android6.0、7.0动态权限所需
        PermissionManager.TPermissionType type=PermissionManager.onRequestPermissionsResult(requestCode,permissions,grantResults);
        PermissionManager.handlePermissionsResult(this,type,invokeParam,this);
    }
    @Override
    public PermissionManager.TPermissionType invoke(InvokeParam invokeParam) {
        PermissionManager.TPermissionType type=PermissionManager.checkPermission(TContextWrap.of(this),invokeParam.getMethod());
        if(PermissionManager.TPermissionType.WAIT.equals(type)){
            this.invokeParam=invokeParam;
        }
        return type;
    }
    /**
     *  获取TakePhoto实例
     * @return
     */
    public TakePhoto getTakePhoto(){
        if (takePhoto==null){
            takePhoto= (TakePhoto) TakePhotoInvocationHandler.of(this).bind(new TakePhotoImpl(this,this));
        }
        return takePhoto;
    }

    private void generalOutputUri(){
        configCompress();
        File file = Utils.generalTempFile(".jpg");
        outputUri = Uri.fromFile(file);
    }
}
